<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-card title="当前状态" :bordered="false" >
          <a-row type="flex" justify="start">
            <a-col :span="12" >
              <tsl-step :list="steplist" :currentStatus="model.stepStatus"></tsl-step>
            </a-col>
<!--            <a-col :span="12" flex="flex-end" style="text-align: right">-->
<!--              <a-button type="primary">提交审批</a-button>-->
<!--            </a-col>-->
          </a-row>
        </a-card>
        <a-divider />
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input disabled v-model="model.code" placeholder="请输入单据编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageType">
              <j-dict-select-tag style="width: 200px" :disabled="storageTypeDisabled" type="list" v-model="model.storageType"
                                 dictCode="rk_type" placeholder="请选择入库类型" :disabledVal="3"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-show="false">
          <a-col :span="6" >
            <a-form-model-item label="宝洁供应商编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjSupplierCode">
              <a-input v-model="model.bjSupplierCode"  placeholder="宝洁供应商编码" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="宝洁采购订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjProcurementCode">
              <a-input v-model="model.bjProcurementCode"  placeholder="宝洁采购订单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="宝洁供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjSupplierName">
              <a-input v-model="model.bjSupplierName"  placeholder="宝洁供应商" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <a-tabs
            :default-active-key="tabkeys[0]"
            >
      <a-tab-pane tab="入库信息" :key="tabkeys[0]"  :forceRender="true">
        <a-card title="收货信息" :bordered='false'>
          <j-vxe-table
             keep-source
            :ref="refKeys[0]"
            :loading="bussStorageNoticeMaterialTable.loading"
            :columns="bussStorageNoticeMaterialTable.columns"
            :dataSource="bussStorageNoticeMaterialTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            :toolbarConfig="{slot: ['prefix', 'suffix'], btn: ['clearSelection']}"
            @selectRowChange="selectRowChange"
            class="bold-border"
             @edit-closed="editMaterialClosedEvent"
          >
            <template    v-slot:toolbarSuffix>
<!--              <a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增</a-button>-->
              <a-button @click='addMaterialInfo' v-show="!bussinessDisable">新增</a-button>
<!--              <a-button @click='addMaterial' >新增</a-button>-->
<!--              <a-button @click='editMaterial' >编辑</a-button>-->
              <a-button @click='deleteMaterial' >删除</a-button>
              <a-button @click='handleCK' >添加车辆信息</a-button>
              <a-button @click='clearCheck("materical")' >清空选择</a-button>
<!--          <a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增物料</a-button>-->
            </template>
            <template v-slot:erpLocationName="props">
              <tsl-warehouse v-model="props.value" :disabled="formDisabled" :rowData='props' @handlerOk="warehouseOk"></tsl-warehouse>
            </template>
            <template v-slot:supplierId="props">
              <tsl-mat-supplier v-model="props.value" :isDisabled="bussinessDisable" :rowData='props'
                                @handlerOk="supplierOk"></tsl-mat-supplier>
            </template>

          </j-vxe-table>
        </a-card>
        <a-card title="车辆信息" :bordered='false'>
          <j-vxe-table
            keep-source
            :ref="refKeys[1]"
            :loading="bussStorageNoticeCarinfoTable.loading"
            :columns="bussStorageNoticeCarinfoTable.columns"
            :dataSource="bussStorageNoticeCarinfoTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            :autoResize="true"
            :toolbarConfig="{slot: ['prefix', 'suffix'], btn: ['clearSelection']}"
            @edit-closed="editClosedEvent"
          >
            <template    v-slot:toolbarSuffix>
<!--                            <a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增</a-button>-->
<!--              <a-button @click='editCarInfo' >编辑</a-button>-->
              <a-button @click='deleteCarinfo' >删除</a-button>
              <a-button @click='clearCheck("car")' >清空选择</a-button>
              <!--<a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增物料</a-button>-->
            </template>
          </j-vxe-table>
        </a-card>
      </a-tab-pane>
      <a-tab-pane tab="状态履历修改" :key="tabkeys[1]"  :forceRender="true">
        <a-card :bordered='false'>
          <tsl-history  dataTable="buss_storage_notice"  :dataId="model.id"></tsl-history>
        </a-card>
      </a-tab-pane>
    </a-tabs>

    <!-- 采购单 -->
    <buss-material-procurement-list
                ref='procurement' @handleOk='procurementOk' :procurementType='procurementType' checkval='checkbox'></buss-material-procurement-list>
    <erp-supplier-list ref='supplier' @handlerOk='supplierOk'> </erp-supplier-list>

    <erp-good-list ref='good'
                   @handlerOk='goodOk'
                   checkval='checkbox'
                   :supplierId="model.supplierId"></erp-good-list>
    <bussiness-type-list ref="bussinessType" @handleOk="bussinessOk" :businessNode="0" :businessType="1"></bussiness-type-list>
  </a-spin>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import BussMaterialProcurementList  from '@/views/modules/procurement/BussMaterialProcurementList'
  import ErpSupplierList from '@/views/modules/supplier/ErpSupplierList'
  import ErpGoodList from '@/views/modules/goods/ErpGoodsListModal'
  import ErpLocationList from '@/views/modules/location/ErpLocationList'
  import DetailsModal from '@/components/modal/DetailsModal'
  import TslStep from '@/components/tsl/TslStep'
  import BussinessTypeList from '@/views/modules/business/BusinessTypeList'
  import moment from 'dayjs'
  import TslWarehouse from '@comp/tsl/TslWarehouse.vue'
  import TslMatSupplier from '@comp/tsl/cell/TslMatSupplier.vue'
  import TslHistory from '@comp/tsl/TslHistory.vue'

  export default {
    name: 'BussStorageNoticeForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,BussMaterialProcurementList,ErpSupplierList,ErpGoodList,ErpLocationList,
      DetailsModal,TslStep,BussinessTypeList,TslWarehouse,TslMatSupplier,TslHistory
    },
    data() {
      const actualNum = (rule, value, callback) => {
        callback(new Error('请再次输入密码'));
        // if (value === '') {
        //   callback(new Error('请再次输入密码'));
        // } else if (value !== this.formInfo.password) {
        //   callback(new Error('两次密码不同'));
        // } else {
        //   callback();
        // }
      };
      return {
        // bussinessDisable: false,
        procSelectRows: [],
        toolBtn: [ 'remove', 'clearSelection'],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          stepStatus: 0
         },
        steplist:[
          {title:'草稿'},{title:'采购确认'},{title:'入库'}
        ],
        rules: {
          num: [
            {required: true, message: '必须输入序号'},
          ],
          actualNum: [
            // { required: true, trigger: "blur", validator: actualNum },
          ]
        },
        noticeMaterialRowNum: 0,
        carRowNum: 0,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        validatorRules: {
        },
        historyOption: [],
        refKeys: ['bussStorageNoticeMaterial', 'bussStorageNoticeCarinfo', ],
        tableKeys:['bussStorageNoticeMaterial', 'bussStorageNoticeCarinfo', ],
        tabkeys: ['material','uphistorys'],
        activeKey: 'material',
        // 入库通知单原料单
        bussStorageNoticeMaterialTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '行项目',
              key: 'rowNum',
              type: JVXETypes.normal,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '通知id',
              key: 'noticeId',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '仓库编号',
              key: 'erpWarehouseCode',
              type: JVXETypes.hidden,
              width: '100px',
            },
            {
              title: '仓库名称',
              key: 'erpWarehouseName',
              type: JVXETypes.hidden,
              width: '100px',
            },
            {
              title: '库位编码',
              key: 'erpLocationCode',
              type: JVXETypes.hidden,
              width: '100px',
            },
            // {
            //   title: '库位名称',
            //   key: 'erpLocationName',
            //   type: JVXETypes.slot,
            //   width: '200px',
            //   slotName: 'erpLocationName',
            // },
            {
              title: '库位名称',
              key: 'erpLocationId',
              type: JVXETypes.slot,
              slotName: 'erpLocationName',
              width: '150px',
            },
            {
              title: '批次号',
              key: 'batchNum',
              type: JVXETypes.input,
              width: '120px',
            },
            {
              title: '物料批号',
              key: 'materialLotNum',
              type: JVXETypes.input,
              width: '120px',
            },
            {
              title: '原发数量',
              key: 'originalNum',
              type: JVXETypes.normal,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '实收数量',
              key: 'actualNum',
              type: JVXETypes.normal,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '入库日期',
              key: 'warehouseDate',
              type: JVXETypes.date,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '生产日期',
              key: 'createDate',
              type: JVXETypes.date,
              width:"120px",
              placeholder: '请输入${title}',
            },
            {
              title: '限用日期',
              key: 'expiryDate',
              type: JVXETypes.date,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格',
              key: 'spec',
              type: JVXETypes.normal,
              width: '70px',
            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.selectSearch,
              width: '70px',
              dictCode: 'ji_unit',
              // disabled: true

            },
            {
              title: '供应商',
              key: 'supplierId',
              type: JVXETypes.slot,
              width: '200px',
              slotName: 'supplierId',
            },
            {
              title: '供应商',
              key: 'supplierName',
              type: JVXETypes.hidden,
              width: '100px',
            },
            {
              title: '采购订单编号',
              key: 'procurementCode',
              type: JVXETypes.normal,
              width: '120px',
            },
            {
              title: '排产单号',
              key: 'schedulingCode',
              type: JVXETypes.input,
              width: '120px',
            },
            {
              title: '采购明细id',
              key: 'procurementDetailId',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '原料id',
              key: 'materialId',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '采购数量',
              key: 'procurementNum',
              type: JVXETypes.normal,
              width: '120px',
            },
            {
              title: '辅助数量',
              key: 'supportNum',
              type: JVXETypes.normal,
              width: '120px',
            },
            {
              title: '辅助单位',
              key: 'supportUnit',
              type: JVXETypes.normal,
              width: '70px',
            },
            {
              title: '已到货数量-未作',
              key: 'procurementNum',
              type: JVXETypes.normal,
              width: '70px',
            },
            {
              title: '当前状态',
              key: 'status',
              type: JVXETypes.hidden,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            // {
            //   title: '操作',
            //   key: 'action',
            //   type: JVXETypes.slot,
            //   fixed: 'right',
            //   minWidth: '200px',
            //   align: 'center',
            //   slotName: 'action',
            // }
          ]
        },
        // 入库通知单-车辆信息
        bussStorageNoticeCarinfoTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'id',
              key: 'id',
              type: JVXETypes.hidden,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '行项目',
              key: 'rowNum',
              type: JVXETypes.normal,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '通知单id',
              key: 'noticeId',
              type: JVXETypes.hidden,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '车牌号',
              key: 'carNum',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.select,
              width: '150px',
              dictCode: 'ji_unit',
              disabled: true
            },
            {
              title: '原发数',
              key: 'originalNum',
              type: JVXETypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '实际数量',
              key: 'actualNum',
              type: JVXETypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            // {
            //   title: '操作',
            //   key: 'action',
            //   type: JVXETypes.slot,
            //   fixed: 'right',
            //   minWidth: '200px',
            //   align: 'center',
            //   slotName: 'action',
            // }
          ]
        },
        NoticeMaterialTable: '',
        CarTableRef: '',
        url: {
          add: "/business/bussStorageNotice/add",
          edit: "/business/bussStorageNotice/edit",
          queryById: "/business/bussStorageNotice/queryById",
          bussStorageNoticeCarinfo: {
            list: '/business/bussStorageNotice/queryBussStorageNoticeCarinfoByMainId'
          },
          bussStorageNoticeMaterial: {
            list: '/business/bussStorageNotice/queryBussStorageNoticeMaterialByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      /*流程自定义表单数据*/
      customFormData:{
        type:Object,
        default:()=>{return {}},
        required:false
      },
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      procurementType(){
        return this.model.materialTypeName === '包材'?1:0;
        // return this.model.type | 0
      },
      procurementShow: {
        get(){
          if(typeof this.model.type === 'undefined'){
            return false
          }
          if((this.model.type == 0 || this.model.type == 1) && (this.model.arrayType)){
            return false
          }
          return this.model.type == 0 || this.model.type == 1
        },
        set(){}
      },
      showProcurement() {
        if(this.model.type && (this.model.type == 0 || this.model.type == 1) && (!this.model.arrayType || this.model.arrayType == '')){
          return false;
        }
        return true;
      },
      showSupplier(){
        if(this.model.type && this.model.type == 2){
          return false;
        }
        return true;
      },
      bussinessDisable(){
        if(this.model.businessType  && this.model.businessType == 0){
          return true;
        }
        return false;
      }
    },
    created () {
      if(this.customFormData != null) {
        console.log("this.customFormData=",this.customFormData);
        this.model = this.customFormData;
        this.editAfter();  //现在子表内容需要
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.getAllTable().then(tables=>{
          this.NoticeMaterialTable = tables[0]
          this.CarTableRef = tables[1]
        })
        setTimeout(() => {
          if(!this.model.id){
            let rows = this.NoticeMaterialTable.getNewDataWithId()
            this.NoticeMaterialTable.removeRowsById(rows[0].id)
            let rows_car = this.CarTableRef.getNewDataWithId()
            this.CarTableRef.removeRowsById(rows_car[0].id)
            this.NoticeMaterialTable.syncHeaderScroll = true;
            this.CarTableRef.syncHeaderScroll = true;
          }
          this.scrollTop()
        },500)
      })
    },
    methods: {
      // loadOption(){
      //   getAction('/sys/dataLog/list/log',{
      //     dataId: this.model.id,
      //     dataTable: 'buss_storage_notice'
      //   }).then(res=>{
      //     //historyOption
      //     console.log('历史数据',res)
      //   })
      // },
      warehouseOk({result,row}){
        this.bussStorageNoticeMaterialTable.dataSource.forEach(item=>{
            if(item.materialId == row.materialId && item.rowNum == row.rowNum){
              item.erpLocationId = result.id
              item.erpLocationName = result.name
              item.erpLocationCode = result.code
              item.erpWarehouseName = result.warehouseName
              item.erpWarehouseCode = result.warehouseCode
            }
        })
        this.scrollTop()
      },
      editMaterialClosedEvent({ row, column }){
        let xTable = this.$refs.bussStorageNoticeMaterial
        let field = column.property
        console.log(field)
        let cellValue = row[field]
        // 判断单元格值是否被修改
        this.$nextTick(() => {
          if('batchNum' === field){
            if (xTable.isUpdateByRow(row, field)) {
              this.bussStorageNoticeMaterialTable.dataSource.forEach(mater => {
                mater.batchNum = cellValue
              })
            }
          }
        })
      },
      editClosedEvent ({ row, column }){
        // 车辆数量修改，物料数量跟着变动
        let xTable = this.$refs.bussStorageNoticeCarinfo
        let field = column.property
        let cellValue = row[field]
        // 判断单元格值是否被修改
        this.$nextTick(() => {
          if (xTable.isUpdateByRow(row, field)) {
            let { rowNum, materialId, originalNum, actualNum } = row
            this.bussStorageNoticeMaterialTable.dataSource.forEach(mater => {
                 mater.actualNum = 0
                 mater.originalNum = 0
                this.bussStorageNoticeCarinfoTable.dataSource.forEach(car =>{
                  if(car.rowNum === mater.rowNum && mater.materialId === car.materialId ){
                    mater.actualNum +=  car.actualNum
                    mater.originalNum += car.originalNum
                  }
                })
                // let totalActualNum =  this.bussStorageNoticeCarinfoTable.dataSource.reduce((accumulator, currentValue) => {
                //   return accumulator + currentValue['actualNum'];
                // }, 0);
                // let totalOriginalNum = this.bussStorageNoticeCarinfoTable.dataSource.reduce((accumulator, currentValue) => {
                //   return accumulator + currentValue['originalNum'];
                // }, 0);
                // mater.actualNum = totalActualNum
                // mater.originalNum = totalOriginalNum
            });
            this.NoticeMaterialTable.resetScrollTop();
          }
        })
      },
      edit(record) {
        if (typeof this.editBefore === 'function') this.editBefore(record)
        this.visible = true
        this.activeKey = this.refKeys[0]
        this.$refs.form.resetFields()
        this.model = Object.assign({}, record)
        if (typeof this.editAfter === 'function') this.editAfter(this.model)
      },
      addProc(){
        if(this.procSelectRows.length>0){
          const rows = this.procSelectRows
          //判断是否存在不同的供应商
          // let jsonarray = rows.map((item,index)=>({
          //   ...item,
          //   id: '',
          //   procurementCode: item.code,
          //   procurementDetailId: item.id,
          //   rowNum: this.getRowNum(),
          //   warehouseDate: moment(new Date()).format('YYYY-MM-DD'),
          // }))
          rows.forEach((item,index)=>{
            let detail = {}
            detail.rowNum = this.getRowNum()
            detail.procurementCode = item.code
            detail.procurementDetailId = item.id
            detail.warehouseDate = moment(new Date()).format('YYYY-MM-DD')
            detail.materialId = item.materialId
            detail.materialName = item.materialName
            detail.materialCode = item.materialCode
            detail.supplierId = item.supplierId
            detail.supplierCode = item.supplierCode
            detail.meUnit = item.meUnit
            detail.procurementNum = item.procurementNum
            this.bussStorageNoticeMaterialTable.dataSource.push(detail)
          })
          this.$nextTick(()=>{
            // this.bussStorageNoticeMaterialTable.dataSource.push(... jsonarray)
            this.confirmBussiness(rows[0].materialId);
          })
        }
        this.getPfCode()
      },
      confirmBussiness(materialId){
        getAction("/business/businessType/info",{businessNode:0,businessType:0,materialId:materialId}).then(res=>{
          if(res.success){
            const {result} = res
            this.$set(this.model,'businessNode',result.businessNode)
            this.$set(this.model,'materialTypeName',result.materialTypeName)
            this.$set(this.model,'materialTypeCode',result.materialTypeCode)
            this.$set(this.model,'businessType',result.businessType)
          }
        })
      },
      onSearchBussiness(){
        this.$nextTick(()=>{
          this.$refs.bussinessType.add();
        })
      },
      bussinessOk({rows,callback}){
        const row = rows[0]
        this.$set(this.model,'businessNode',row.businessNode)
        this.$set(this.model,'materialTypeName',row.materialTypeName)
        this.$set(this.model,'materialTypeCode',row.materialTypeCode)
        this.$set(this.model,'businessType',row.businessType)
        // this.model.businessNode = row.businessNode
        // this.model.materialTypeName = row.materialTypeName
        // this.model.businessType = row.businessType
        callback(true)
      },
      addMaterialInfo(){
        if(!this.model.businessType){
          this.$message.warn('请选择业务节点！')
          return;
        }
        if(this.model.businessType == 0){
          //采购
          this.onSearchProcurement()
        }else{
          //
          this.onSearchMaterial();
        }
        // let props = {}
        // props.row = {}
        // this.$refs.details.open(props,this.bussStorageNoticeMaterialTable.dataSource)
      },
      // addMaterialInfo(){
      //   if(!this.model.businessType){
      //     this.$message.warn('请选择业务节点！')
      //     return;
      //   }
      //   // let props = {}
      //   // props.row = {}
      //   // this.$refs.details.open(props,this.bussStorageNoticeMaterialTable.dataSource)
      // },
      locationOk(data){
        this.$refs.details.updateData('erpWarehouseCode',data.warehouseCode)
        this.$refs.details.updateData('erpWarehouseName',data.warehouseName)
        this.$refs.details.updateData('erpLocationCode',data.code)
        this.$refs.details.updateData('erpLocationName',data.name)
        this.$refs.details.updateData('erpLocationId',data.id)
      },
      onSelectLocation(){
        this.$refs.location.add();
      },
      deleteCarinfo(props){
        // 删除物料
        let rows =  this.CarTableRef.selectedRows;
        if(rows.length<=0){
          this.$message.warn('请选择车辆信息！')
          return;
        }
        rows.forEach(row=>{
          this.bussStorageNoticeCarinfoTable.dataSource = this.bussStorageNoticeCarinfoTable.dataSource.filter(item=>item.id !== row.id)
        })
      },
      handleEdit(props){
        this.noticeMaterialRowNum = props.index
        this.$refs.details.open(props,this.bussStorageNoticeMaterialTable.dataSource)
      },
      editCarInfo(){
        let rows = this.CarTableRef.selectedRows
        if(rows.length == 0 || rows.length > 1){
          this.$message.warn('请选择一个要编辑的车辆信息！')
          return;
        }
        const index = this.bussStorageNoticeCarinfoTable.dataSource.findIndex(obj => obj.id === rows[0].id);
        if(index == -1){
          this.$message.warn('请选择一个要编辑的车辆信息！')
          return;
        }
        let props = {}
        props.index = index
        props.row = rows[0]
        this.$refs.carDetail.open(props,this.bussStorageNoticeCarinfoTable.dataSource)
      },
      handleCK(){
        // 添加车辆信息
        let rows =  this.NoticeMaterialTable.selectedRows;
        if(rows.length === 0 || rows.length > 1){
          this.$message.warn('请选择一个收货信息！')
          return;
        }
        rows.forEach(item=>{
          let detail = {
            actualNum: '',
            originalNum: '',
            rowNum: item.rowNum,
            materialId: item.materialId,
            materialCode: item.materialCode,
            materialName: item.materialName,
            meUnit: item.meUnit
          }
          this.bussStorageNoticeCarinfoTable.dataSource.push(detail)
        })
        // let newarray = rows.map(item=>({
        //   ...item,
        //     id: '',
        //     actualNum: '',
        //     originalNum: ''
        // }))
        // this.bussStorageNoticeCarinfoTable.dataSource.push(... newarray)
      },
      selectRowChange({type,action,selectedRows,$event}){
        if(selectedRows.length.length > 1 || selectedRows.length.length == 0){
          $event.$table.clearFilter()
        }else {
          if(this.bussStorageNoticeCarinfoTable.dataSource.length>0){
            const  row = selectedRows[0]
            this.filterCarEvent(row.rowNum,row.materialId,$event);
          }
        }
      },
      filterCarEvent (rowNum,materialId,$event) {
        //筛选有问题
        // const xTable = this.$refs.this.$refs.bussStorageNoticeCarinfo
        // const column = $event.$table.getColumnByField('rowNum')
        // console.log(column)
        // // 修改第一个选项为勾选状态
        // // const option = column.filters[0]
        // // option.data = rowNum
        // const column1 = $event.$table.getColumnByField('materialId')
        // // const option1 = column.filters[0]
        // // option1.data = rowNum
        // // option.checked = true
        // $event.$table.setFilter(column, rowNum)
        // $event.$table.setFilter(column1, materialId)
        // // 修改条件之后，需要手动调用 updateData 处理表格数据
        // $event.$table.updateData()
      },
      getPfCode() {
        postAction('/sys/fillRule/executeRuleByCode/rktzd', {}).then(res => {
          this.model.code = res.result;
        })
      },
      addCarInfo(row){
        let car = {}
        car.materialId = row.materialId
        car.materialName = row.materialName
        car.materialCode = row.materialCode
        car.meUnit = row.meUnit
        // this.bussStorageNoticeCarinfoTable.dataSource.push(car)
        // this.scrollTop()
        let props = {}
        // props.index = index
        props.row = car
        this.$refs.carDetail.open(props,this.bussStorageNoticeCarinfoTable.dataSource)
      },
      deleteCarByMat(code,rowNum){
        // 删除车辆信息
        let data = this.bussStorageNoticeCarinfoTable.dataSource.filter(item=> item.materialCode !== code && item.rowNum !== rowNum)
        this.bussStorageNoticeCarinfoTable.dataSource =  data
      },
      goodOk(rows){
        let _this = this;
        console.log('获取的数据',rows)
        rows.forEach((item,index)=>{
          let obj = {}
          obj.materialId= item.id
          obj.materialName= item.name
          obj.materialCode= item.code
          obj.spec= item.noneSpec
          obj.meUnit= item.meUnit
          obj.rowNum = this.getRowNum()
          obj.warehouseDate = moment(new Date()).format('YYYY-MM-DD')
          this.bussStorageNoticeMaterialTable.dataSource.push(obj)
        })
        this.scrollTop()
        // let filteredJsonArray = jsonArray.filter(item=> {
        //   if(this.bussStorageNoticeMaterialTable.dataSource.length>0){
        //     const alice = this.bussStorageNoticeMaterialTable.dataSource.find(obj => item.materialCode === obj.materialCode && item.supplierId === obj.supplierId);
        //     return !alice;
        //   }
        //   return true;
        // })
        // this.NoticeMaterialTable.pushRows(... filteredJsonArray)
        // this.tableRef.pushRows(jsonarray)
        // this.bussStorageNoticeMaterialTable.dataSource.push(... jsonArray)
      },
      // addMaterial(){
      //   // 新增物料
      //   if(!this.model.arrayType){
      //     this.$message.warn('请选择到货类型！')
      //   }
      //   if(!this.model.arrayType == 0){
      //       // tls
      //      this.onSearchProcurement();
      //   }else{
      //     // 宝洁 客户自带料
      //      this.showGoogs();
      //   }
      // },
      editMaterial(){
        let rows = this.NoticeMaterialTable.selectedRows
        if(rows.length==0 || rows.length > 1){
          this.$message.warn('请选择一个要编辑的收货信息！')
          return;
        }
        const index = this.bussStorageNoticeMaterialTable.dataSource.findIndex(obj => obj.id === rows[0].id);
        if(index == -1){
          this.$message.warn('请选择要编辑的收货信息！')
          return;
        }
        let props = {}
        props.index = index
        props.row = rows[0]
        console.log(props)
        this.handleEdit(props)
      },
      deleteMaterial(){
        // 删除物料
        let rows =  this.NoticeMaterialTable.selectedRows;
        if(rows.length<=0){
          this.$message.warn('请选择收货信息！')
          return;
        }
        rows.forEach(row=>{
          this.bussStorageNoticeMaterialTable.dataSource = this.bussStorageNoticeMaterialTable.dataSource.filter(item=>item.id !== row.id)
          this.deleteCarByMat(row.materialCode,row.rowNum);
        })
      },
      clearCheck(obj){
        if(obj == 'car'){
          this.CarTableRef.clearSelection();
        }else{
          this.NoticeMaterialTable.clearSelection();
        }
      },
      onSearchMaterial(){
        this.$nextTick(() => {
          this.$refs.good.add()
        })
      },
      onSearchSupplier(){
        this.$nextTick(() => {
          this.$refs.supplier.add();
        })
      },
      supplierOk({row,value}){
        // this.$set(this.model,'supplierName',data.name)
        // this.$set(this.model,'supplierId',data.id)
        // const newrows = this.bussStorageNoticeMaterialTable.dataSource.filter(item=> item.supplierId === value );
        // if(newrows.length != this.bussStorageNoticeMaterialTable.dataSource.length){
        //   this.$message.warn('一个入库通知单单只允许同一个供应商！')
        //   return;
        // }
        this.bussStorageNoticeMaterialTable.dataSource.forEach(item=>{
          if(item.materialId == row.materialId && item.rowNum == row.rowNum){
            item.supplierId = value
          }
        })
        this.scrollTop()
      },
      procurementOk({rows,callback}){
        console.log('获取得数据：',rows)
        // this.$refs.details.updateData('erpLocationId',data.id)
        //判断是否存在不同的供应商
        const supplierId = rows[0].supplierId
        const newrows = rows.filter(item=> item.supplierId === supplierId );
        if(newrows.length != rows.length){
          this.$message.warn('一个入库通知单单只能是同一个供应商！')
          return;
        }
        let jsonarray = rows.map(item=>({
          ...item,
          id: '',
          procurementCode: item.code,
          procurementDetailId: item.id,
          warehouseDate: moment(new Date()).format('YYYY-MM-DD'),
        }))
        this.bussStorageNoticeMaterialTable.dataSource.push(... jsonarray)
        // console.log(rows)
        // let row = rows[0]
        // this.$refs.details.updateData('procurementDetailId',row.detailId)
        // this.$refs.details.updateData('procurementCode',row.code)
        // this.$refs.details.updateData('materialId',row.materialId)
        // this.$refs.details.updateData('materialCode',row.materialCode)
        // this.$refs.details.updateData('materialName',row.materialName)
        // this.$refs.details.updateData('spec',row.spec)
        // this.$refs.details.updateData('meUint',row.meUint)
        // this.$refs.details.updateData('procurementNum',row.procurementNum)
        // this.$refs.details.updateData('supplierId',row.supplierId)
        // this.$refs.details.updateData('supplierName',row.supplierName)
        callback(true)
      },
      // checkSupplier(data){
      //   // 检查供应商
      //   if(this.bussStorageNoticeMaterialTable.dataSource.length > 0){
      //     let supplierId = this.bussStorageNoticeMaterialTable.dataSource[0].supplierId
      //     if(data !== supplierId){
      //       this.$message.warn('一个入库通知单单只能是同一个供应商！')
      //       return false;
      //     }
      //   }
      //   return true
      // },
      loadVendor(filteredJsonArray){
        //加载供应商
        const procurment = filteredJsonArray[0];
        this.model.supplierId = procurment.supplierId;
        this.model.supplierName = procurment.supplierName
        // this.model.procurementCode = procurment.code
        // this.model.procurementId = procurment.procurementId
      },
      onSearchProcurement(){
        // 采购订单
        this.$nextTick(() => {
          this.$refs.procurement.add();
        })
      },
      handlerChanged(data){
        this.model.supplierId = ''
        this.model.procurementCode = ''
        this.model.supplierName = ''
        this.addBefore()
        // this.loaded()
      },
      addBefore(){
        this.bussStorageNoticeCarinfoTable.dataSource = []
        this.bussStorageNoticeMaterialTable.dataSource = []
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.bussStorageNoticeCarinfo.list, params, this.bussStorageNoticeCarinfoTable)
          this.requestSubTableData(this.url.bussStorageNoticeMaterial.list, params, this.bussStorageNoticeMaterialTable)
          // this.loadOption()
          //'状态 0 待提交 1 审批中 2 需修改 3 已审批 ',
          if(this.model.status == 3 ){
            this.model.stepStatus = 1
          }

        }
        // this.loaded()
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
        if(allValues.tablesValue[0].tableData.length == 0){
          this.$message.error('请添加收货信息！')
          return false;
        }
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_FAILED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      checkSupplier(){
        // 检查供应商
        if(this.bussStorageNoticeMaterialTable.dataSource.length > 0){
          let supplierId = this.bussStorageNoticeMaterialTable.dataSource[0].supplierId
          const newrows = this.bussStorageNoticeMaterialTable.dataSource.filter(item=> item.supplierId === supplierId );
          if(newrows.length != this.bussStorageNoticeMaterialTable.dataSource.length){
            this.$message.warn('一个入库通知单单只能是同一个供应商！')
            return false;
          }
        }
        return true
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let _this = this;
        let main = Object.assign(this.model, allValues.formValue)
        // if(!this.checkSupplier()){
        //   return;
        // }
        return {
          ...main, // 展开
          bussStorageNoticeMaterialList: _this.processingData( allValues.tablesValue[0].tableData),
          bussStorageNoticeCarinfoList: _this.processingData(allValues.tablesValue[1].tableData),
        }
      },
      processingData(data){
        let newJsonArray = data.map(item => {
          return { ...item, id: item.id && item.id.indexOf('row')>=0?'':item.id  };
        });
        return newJsonArray;
      },
      validateError(msg){
        this.$message.error(msg)
      },
      scrollTop(){
        // 数据变动会出现滚动条无法滚动的情况，调用这个
        this.NoticeMaterialTable.resetScrollTop();
        // this.CarTableRef.resetScrollTop();
        // getRefPromise(this, 'bussStorageNoticeMaterial').then(vxeTable => {
        //   vxeTable.resetScrollTop()
        // })
      },
      handleDetailsConfirm({row,datasource,index, callback}) {
        // 校验当前行 app.$refs['formInline']
        if(datasource === this.bussStorageNoticeMaterialTable.dataSource){
          this.$refs.mainForm.validate(valid=>{
            this.detailsConfirm(valid,row,datasource,index,callback);
            this.NoticeMaterialTable.resetScrollTop();
          })
        }else {
          this.$refs.subForm.validate(valid=>{
            this.detailsConfirm(valid,row,datasource,index,callback);
            this.CarTableRef.resetScrollTop();
          })
        }
      },
      detailsConfirm(valid,row,datasource,index, callback){
        if (valid) {
          callback(true)
          console.log('返回得index：',index)
          if (typeof index !== 'undefined') {
            Object.assign(datasource[index], row);
          }else{
            datasource.push(row);
          }
        } else {
          callback(false)
          this.$message.warn('校验失败')
        }
      },
      getRowNum(){
        let source = this.bussStorageNoticeMaterialTable.dataSource
        if(source.length === 0){
          return '0001'
        }
        let { rowNum } = source[source.length-1]
        let nextRowNum = Number(rowNum) + 1;
        if(nextRowNum < 10){
          return '000'+ nextRowNum;
        }else if(nextRowNum < 100){
          return '00'+ nextRowNum;
        }else if(nextRowNum < 1000){
          return '0'+ nextRowNum;
        }else {
          return String(nextRowNum)
        }
      }
    }
  }
</script>

<style scoped>
</style>
<style>

/*.bold-border .vxe-table--main-wrapper .vxe-table .vxe-body--row .vxe-body--column {*/
/*  border: 2px solid #ccc; !* 设置边框粗细和颜色 *!*/
/*}*/

/*.bold-border .vxe-table--main-wrapper .vxe-table .vxe-footer--column {*/
/*  border-top: 2px solid #ccc; !* 表尾也可以加粗 *!*/
/*}*/

/*.bold-border table, tr, td {*/
/*  border: 1px solid black; !* 黑色边框，1px宽度 *!*/
/*}*/
/*.bold-border table, th, td {*/
/*  border: 1px solid black; !* 黑色边框，1px宽度 *!*/
/*}*/
</style>